import config
conf=config.config()
import utils
import os, gtk, sys
import threading
import plugins

class make_video(threading.Thread):
    def __init__(self, project_folder, list_photo, list_text, list_track, progress, preview=False):
        threading.Thread.__init__(self)
        self.project_folder=project_folder
        self.list_photo=list_photo
        self.list_text=list_text
        self.list_track=list_track
        
        self.progress=progress
        self.preview=preview
        
        self.current_op=0
        self.tot_op=1
        pass
    
    def run(self):
        print "running"
        project_folder=self.project_folder
        if not self.preview:
            frame_width=conf.frame_width
            frame_height=conf.frame_height
            fps=conf.fps
        else:
            frame_width=400
            frame_height=300
            fps=12
        plugin_avaible=plugins.get_child_plugins()
        
        try:
            os.system("rm -R "+ project_folder+"temp/")
        except:pass
        
        
        i=1
        try:
            os.mkdir(project_folder+"temp/")
        except: pass
        
        self.current_op=0
        tot_photo_len=0
        for photo in self.list_photo:
            tot_photo_len+=photo.len
        for text in self.list_text:
            if text.comment!="":
                self.tot_op+=2
        self.tot_op=(fps*tot_photo_len)+1
        
        self.progress.set_tot_operations(self.tot_op)
        
        self.list_process=[]
        
        index=1
        for photo in self.list_photo:
            #Scale picture
            self.check_can_execute()
            pid=utils.execute(["convert", photo.photo ,"-resize", str(frame_width) +"x"+ str(frame_height)+"!", project_folder+"temp/" + str(index) + ".jpg"], False)
            self.list_process.append([pid, "resizing photo " + photo.photo])
            index+=photo.len*fps
        
        for text in self.list_text:
            if text.comment!="":
                self.check_can_execute()
                width=len(text.comment)*50
                print width
                pid=utils.execute(["convert","-size",str(width)+"x85", "xc:transparent", "-font", "Bookman-DemiItalic", "-pointsize", "72", "-draw", "text 25,60 '"+text.comment+"'", "-channel", "RGBA", "-gaussian", "0x6", "-fill", "white", "-stroke", "black", "-draw", "text 20,55 '"+text.comment+"'", "-resize", str(frame_width)+"x100", project_folder+"temp/text" + str(text.id) + ".png"], False)
                self.list_process.append([pid, "creating text"])
        
        
        i=0
        while i<len(self.list_process):
            self.wait(self.list_process.pop(i))
        
        
        
#        index=1
#        for photo in self.list_photo:
#            if os.path.isfile(project_folder+"temp/text" + str(index) + ".png"):
#                self.check_can_execute()
#                pid=utils.execute(["composite", "-gravity", "South", project_folder+"temp/text" + str(index) + ".png", project_folder+"temp/" + str(index) + ".jpg", project_folder+"temp/" + str(index) + ".jpg"], False)
#                self.list_process.append([pid, "Merging text"])
#            index+=photo.len*fps
#        
#        i=0
#        while i<len(self.list_process):
#            self.wait(self.list_process.pop(i))
        
        num_photo=1
        index=1
        for photo in self.list_photo:
            first=index
            i=first+1
            while (i-first<((fps*photo.len)-fps*photo.len_effect)):
                self.check_can_execute()
                pid=utils.execute(["ln", "-f", project_folder+"temp/" + str(first) + ".jpg", project_folder+"temp/" + str(i) + ".jpg"], False)
                self.list_process.append([pid, "copy frame"])
                i+=1
            if num_photo<len(self.list_photo):
                next_foto=project_folder+"temp/" + str(index+photo.len*fps) + ".jpg"
                
                pos=0
                while i-first<(fps*photo.len):
                    pos+=1
                    per=100*pos/(fps*photo.len_effect)
                    
                    self.check_can_execute()
                    if plugin_avaible.has_key(photo.trans_effect):
                        pid=plugin_avaible[photo.trans_effect](project_folder+"temp/" + str(first) + ".jpg", next_foto, project_folder+"temp/" + str(i) + ".jpg", per)
                    else:
                        pid=utils.execute(["composite", "-dissolve", str(per)+"%", "-gravity", "center", next_foto, project_folder+"temp/" + str(first) + ".jpg", project_folder+"temp/" + str(i) + ".jpg"], False)
                    self.list_process.append([pid, "create photo effect frame"])
                    i+=1
            else:
                while i-first<(fps*photo.len):
                    self.check_can_execute()
                    pid=utils.execute(["ln", project_folder+"temp/" + str(first) + ".jpg", project_folder+"temp/" + str(i) + ".jpg"], False)
                    self.list_process.append([pid, "copy photo"])
                    i+=1
            num_photo+=1
            index+=photo.len*fps
        
        i=0
        while i<len(self.list_process):
            self.wait(self.list_process.pop(i))
        
        self.update("converting frames to video with ffmpeg(this may require some times)")
        utils.execute(["ffmpeg", "-f" ,"image2", "-r", str(fps), "-i", project_folder+"temp/%d.jpg", "-y" , "-s", str(conf.frame_width)+"x"+str(conf.frame_height), "-sameq", project_folder + "movie.mpg"])
        
        try:
            os.system("rm -R "+ project_folder+"temp/")
        except:pass
        
        self.update("finish")

    def wait(self, process):
        pid, op=process
        try:
            os.waitpid(pid, 0)
        except:
            print "Process already killed"
        self.update(op)

    def update(self, string):
        gtk.gdk.threads_enter()
        self.progress.update(string)
        gtk.gdk.threads_leave()
    
    def check_can_execute(self):
        if len(self.list_process)>conf.max_parallel_process:
            self.wait(self.list_process.pop(0))
            